<?php

namespace App\Http\Controllers;

use App\Exceptions\API\AuthorizationFailed;
use App\Models\User;
use Illuminate\Http\Request;
use Zend\Diactoros\Response as Psr7Response;

class AuthController
{

    public function getToken(Request $request)
    {
        $headers = [
            'Content-Type' => 'application/json',
        ];
        $data =  [
            'client_id' => config('teambition.client_id'),
            'client_secret' => config('teambition.client_secret'),
            'code' => $request->get('code')
        ];
        $res = sunmi_post('https://account.teambition.com/oauth2/access_token',$data,$headers);

        if (isset($res['status'])) {
            throw new AuthorizationFailed('auth error');
        }
        $user = $this->getUserByToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfdXNlcklkIjoiNTlmOTM3ZmExYjQ1NGYxOGRjZTcwYzdjIiwiYXVkIjoib2F1dGgyIiwiYXV0aFVwZGF0ZWQiOjAsImNsaWVudEtleSI6ImU2OGQ2N2YwLWMwNmItMTFlNy04YmY4LTk3NTNlMmU3YWQwOSIsImV4cCI6MTU0MTkzMDQzNywiaXNzIjoiYWNjb3VudHMifQ.JixPwd2t2lvY5RUyMH7UGK7ypOKoP32mD_WQRxNoCRc');

        ;

        return ['token_type' => 'Bearer', 'access_token' => $user->createToken('sunmi')->accessToken];

    }

    private function getUserByToken($token)
    {

        $headers = [
            'Content-Type' => 'application/json',
            'Authorization'  => 'OAuth2 '.$token,
        ];

        $res = sunmi_get('https://api.teambition.com/users/me', null ,$headers);

//        $client = new Client(['headers' => [
//            'Content-Type' => 'application/json',
//            'Authorization'  => 'OAuth2 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfdXNlcklkIjoiNTlmOTM3ZmExYjQ1NGYxOGRjZTcwYzdjIiwiYXVkIjoib2F1dGgyIiwiYXV0aFVwZGF0ZWQiOjAsImNsaWVudEtleSI6ImU2OGQ2N2YwLWMwNmItMTFlNy04YmY4LTk3NTNlMmU3YWQwOSIsImV4cCI6MTU0MTkwNjU0NCwiaXNzIjoiYWNjb3VudHMifQ.I5unR4leE5bnCvl1xUY4-Yj5DePMQMt1aqe7hf2ofIQ'
//        ],]);
//        $res = $client->request('GET', 'https://api.teambition.com/users/me');
        if (isset($res->code)) {
            throw new AuthorizationFailed('auth error');
        }
        $users = User::query()->where('teambition_sign', $res->_id)->get();

        if ($users ->isEmpty()) {
            throw new AuthorizationFailed('user not found');
        }

        $user = $users->first();
        $user->teambition_token = $token;
        $user->save();


        return $user;

    }

}
